﻿using Mapster;
using Microsoft.AspNetCore.Http;
using MimeKit.Encodings;
using Org.BouncyCastle.Asn1.X509;
using Plugin.Archives.Models;
using RsCode;
using RsCode.Domain;
using System.Linq;

namespace Plugin.Archives.Service
{
	public class BmAppService
	{
        IRepository<BaomingInfo> repository;
        IHttpContextAccessor httpContextAccessor;
		Dictionary<string, string> dic = new Dictionary<string, string>();
		public BmAppService(IRepository<BaomingInfo> repository,IHttpContextAccessor httpContextAccessor)
        {
            this.repository = repository;
            this.httpContextAccessor = httpContextAccessor;
            dic.Add("就业", "1");
			dic.Add("志愿者", "2");
			dic.Add("医学", "3");
			dic.Add("国学", "4");
			dic.Add("演说", "5");
			dic.Add("健身", "6");
			dic.Add("合作加盟", "7");
			dic.Add("水电技工", "8");
		}

		string LoginUserId
		{
			get
			{
				var claims = httpContextAccessor?.HttpContext?.User.Claims;
				return claims?.First(x => x.Type == "UserId").Value ?? "";
			}
		}
		public async Task<object>SaveAsync(BaomingEditDto dto)
        {
            var info =await repository.Select.Where(x => x.Phone == dto.Phone).ToOneAsync();
            if (info != null)
                throw new AppException("该手机号己参与过报名");
            var entity = dto.Adapt<BaomingInfo>();
            entity.UserId= LoginUserId;
            await Task.Run(() => { repository.InsertOrUpdate(entity);});
            return "保存成功";
        } 
    
        public async Task<object> GetAsync(long id)
        {
            var info =await repository.Select.Where(x => x.Id == id).ToOneAsync();
            return info;
        }

        public async Task<object> PageInfoAsync(int page,int pageSize)
        {
			PageData<BaomingInfo> target = new PageData<BaomingInfo>();
			var claims = httpContextAccessor?.HttpContext?.User.Claims;
			var role= claims?.First(x => x.Type == "Role").Value ?? "";
            if(role=="2")
            {
                var select = repository.Select.Include(x=>x.UserInfo).OrderByDescending(x => x.Id);
				target= await repository.PageAsync(page, pageSize,select);
            }else
            {
                var select = repository.Select.Include(x => x.UserInfo).Where(x => x.UserId == LoginUserId).OrderByDescending(x => x.Id);
				target= await repository.PageAsync(page,pageSize,select);
			}

			return target.Adapt<PageData<BaomingInfoDto>>();
		}

        public  async Task<object> SearchBmAsync(SearchDto dto)
        {
            PageData<BaomingInfo> target = new PageData<BaomingInfo>();
            if(dto.Where=="phone")
            {
                var select= repository.Select.Include(x => x.UserInfo).Where(x => x.Phone == dto.Key).OrderByDescending(x=>x.Id);
				target= await repository.PageAsync(dto.Page, dto.PageSize, select);
            }
			if (dto.Where == "area")
			{
				var select = repository.Select.Include(x => x.UserInfo).Where(x => x.Area.Contains(dto.Key)).OrderByDescending(x => x.Id);
				target = await repository.PageAsync(dto.Page, dto.PageSize, select);
			}
			if (dto.Where == "interest")
			{
                var insertest = dic.FirstOrDefault(x => x.Key == dto.Key);
                if(!string.IsNullOrWhiteSpace(insertest.Value))
                {
					var select = repository.Select.Include(x => x.UserInfo).Where(x => x.InterestData.Contains(insertest.Value)).OrderByDescending(x => x.Id);
					target = await repository.PageAsync(dto.Page, dto.PageSize, select);
				}
				

			}
			if (dto.Where == "status")
			{
                int status = 0;
                if(int.TryParse(dto.Key,out status))
                {
					var select = repository.Select.Include(x => x.UserInfo).Where(x => x.Status ==status).OrderByDescending(x => x.Id);
					target = await repository.PageAsync(dto.Page, dto.PageSize, select);
				}
			}

            return target.Adapt<PageData<BaomingInfoDto>>();
		}

        public async Task<object> DeleteAsync(long id)
        {
            await Task.Run(() =>
            {
                repository.Delete(x => x.Id == id);
            });
            return "ok";
        }


        public async Task<object>StatAsync()
        {
           var count= await repository.Select.Where(x=>x.UserId==LoginUserId).CountAsync();
            return new
            {
                count=count
            };
        }

        public async Task<object> RankAsync()
        {

            var start = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
            var end = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
            var ret =await repository.Select
                .Include(x => x.UserInfo)
                .Where(x => x.CreateDate >= start && x.CreateDate <= end).Limit(20)
                .GroupBy(x => x.UserId)
                .OrderByDescending(g => g.Count())
                .ToListAsync(a => new {name= a.Value.UserInfo.Nick, inviteCount=a.Count()})
               ;

            return ret;
        }
    }
}
